package nebula

import (
	"fmt"
	"strconv"
	"tupu-go/pkg/database"
)

// QueryService 通用查询服务
type QueryService struct{}

// AttributeFilter 属性过滤条件
type AttributeFilter struct {
	Attribute string `json:"attribute"` // 属性名
	Type      string `json:"type"`      // 数据类型：string/int/float/bool等
	Operator  string `json:"operator"`  // 操作符：=, !=, >, >=, <, <=, LIKE, IN等
	Value     string `json:"value"`     // 属性值
}

// NodeQueryRequest 节点查询请求
type NodeQueryRequest struct {
	TaskID     int               `json:"task_id"`    // 任务ID
	NodeType   string            `json:"node_type"`  // 节点类型：person/account/card等
	Attributes []AttributeFilter `json:"attributes"` // 属性过滤条件列表
	PageNum    int               `json:"page_num"`   // 页码
	PageSize   int               `json:"page_size"`  // 每页大小
}

// EdgeQueryRequest 边查询请求
type EdgeQueryRequest struct {
	TaskID     int               `json:"task_id"`    // 任务ID
	EdgeType   string            `json:"edge_type"`  // 边类型
	Attributes []AttributeFilter `json:"attributes"` // 属性过滤条件列表
	PageNum    int               `json:"page_num"`   // 页码
	PageSize   int               `json:"page_size"`  // 每页大小
}

// RelationQueryRequest 关系查询请求
type RelationQueryRequest struct {
	TaskID   int    `json:"task_id"`   // 任务ID
	NodeID   string `json:"node_id"`   // 节点ID
	EdgeType string `json:"edge_type"` // 边类型（可选）
	PageNum  int    `json:"page_num"`  // 页码
	PageSize int    `json:"page_size"` // 每页大小
}

// QueryResult 查询结果
type QueryResult struct {
	Data       []map[string]interface{} `json:"data"`        // 查询结果数据
	Total      int                      `json:"total"`       // 总记录数
	PageNum    int                      `json:"page_num"`    // 当前页码
	PageSize   int                      `json:"page_size"`   // 每页大小
	TotalPages int                      `json:"total_pages"` // 总页数
}

// QueryNodes 节点列表模糊分页查询
func (qs *QueryService) QueryNodes(req *NodeQueryRequest) (*QueryResult, error) {
	db := database.GetNDB()

	taskVertexID := req.TaskID

	baseDB := db.Go(taskVertexID).Over("属于")

	for _, attr := range req.Attributes {
		// 构建属性路径
		attrPath := fmt.Sprintf("properties($$).%s", attr.Attribute)

		// 根据操作符构建条件表达式
		var condition string
		var args []interface{}

		switch attr.Operator {
		case "LIKE":
			condition = fmt.Sprintf("%s LIKE ?", attrPath)
			args = []interface{}{"%" + attr.Value + "%"}
		case "=":
			condition = fmt.Sprintf("%s == ?", attrPath)
			args = []interface{}{attr.Value}
		case ">=":
			condition = fmt.Sprintf("%s >= ?", attrPath)
			args = []interface{}{attr.Value}
		case "<=":
			condition = fmt.Sprintf("%s <= ?", attrPath)
			args = []interface{}{attr.Value}
		case ">":
			condition = fmt.Sprintf("%s > ?", attrPath)
			args = []interface{}{attr.Value}
		case "<":
			condition = fmt.Sprintf("%s < ?", attrPath)
			args = []interface{}{attr.Value}
		default:
			return nil, fmt.Errorf("unsupported operator: %s", attr.Operator)
		}

		// 根据类型进行值转换
		switch attr.Type {
		case "int":
			val, err := strconv.Atoi(attr.Value)
			if err != nil {
				return nil, fmt.Errorf("invalid int value for attribute %s: %v", attr.Attribute, err)
			}
			args[0] = val
		case "float":
			val, err := strconv.ParseFloat(attr.Value, 64)
			if err != nil {
				return nil, fmt.Errorf("invalid float value for attribute %s: %v", attr.Attribute, err)
			}
			args[0] = val
		case "bool":
			val, err := strconv.ParseBool(attr.Value)
			if err != nil {
				return nil, fmt.Errorf("invalid bool value for attribute %s: %v", attr.Attribute, err)
			}
			args[0] = val
		}
		baseDB = baseDB.Where(condition, args...)
	}
	var nodes = make([]map[string]interface{}, 0)
	//err := baseDB.Yield("count($$) as count").Find(&countResult)
	err := baseDB.Yield("$$ as node").FindCol("node", &nodes)
	if err != nil {
		return nil, err
	}

	offset := (req.PageNum - 1) * req.PageSize
	baseDB = baseDB.Limit(req.PageSize, req.PageNum*req.PageSize)
	fmt.Println(baseDB, offset)
	return &QueryResult{
		Data:     nodes,
		PageNum:  req.PageNum,
		PageSize: req.PageSize,
	}, nil
}

type GraphPathQueryRequest struct {
	TaskID      int64         `json:"task_id"`
	StartNode   StartNode     `json:"start_node"`
	PathPattern []PathSegment `json:"path_pattern"`
	MaxDepth    int           `json:"max_depth,omitempty"`
	PageNum     int           `json:"page_num"`
	PageSize    int           `json:"page_size"`
}

type StartNode struct {
	Type    string            `json:"type"`
	Filters map[string]Filter `json:"filters"`
}

type PathSegment struct {
	EdgeType  string            `json:"edge_type,omitempty"`
	Direction string            `json:"direction,omitempty"` // "out" 或 "in"
	NodeType  string            `json:"node_type,omitempty"`
	Filters   map[string]Filter `json:"filters,omitempty"`
}

type Filter struct {
	Type     string      `json:"type"`
	Operator string      `json:"operator"`
	Value    interface{} `json:"value"`
}

// QueryRelations 通用关系路径查询
func (qs *QueryService) QueryRelations(req *RelationQueryRequest) (*QueryResult, error) {

	return &QueryResult{}, nil

}
